const request  = require('request')


const corpid = "xxxxx"
const corpsecret="xxxxxx" 

// 获取access_token 默认的是get请求
var getAccess_token = ()=>{
	return new Promise((resolve,reject)=>{
		var url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='+corpid+'&corpsecret='+corpsecret;
		request(url,(error,response,body)=>{
			if(!error &response.statusCode == 200) {
				var temp = JSON.parse(body)
				resolve(temp.access_token)
			}else{
				resolve(error);
			}
		})
	})
}

// 获取userid
var getUserId = (access_token, code)=>{
	return new Promise((resolve,reject)=>{
		var url =  'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='+access_token+'&code='+code;
		request(url,(error,response,body)=>{
			if(!error & response.statusCode ==200){
				resolve(JSON.parse(body));
			} 
		})		
	})
}

// 获取userinfo(通过userID)
var getUserInfo  = (access_token,user_id)=>{
	return new Promise((resolve,reject)=>{
		var url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='+access_token+'&userid='+user_id;
		request(url,(error,response,body)=>{
			if(!error & response.statusCode == 200){
				resolve(JSON.parse(body));	
			}
		})	
	})
}

// 发送get请求
var doGET  = (url)=>{
	return new Promise((resolve,reject)=>{				
		request(url,(error,response,body)=>{
			if(!error & response.statusCode == 200){
				resolve(body);	
			}
		})	
	})
}


// 导出
exports.getAccess_token_ = getAccess_token
exports.getUserInfo_ = getUserInfo
exports.getUserId_  = getUserId
exports.doGET_ = doGET